package com.srwl.mytx.converter;

import android.text.TextUtils;
import android.util.Log;

import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.utils.AESUtil;
import com.srwl.mytx.utils.HttpEncryptUtil;

import java.io.IOException;
import java.nio.charset.Charset;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

public class EncryptInterceptor implements Interceptor {
    private static final String TAG = "EncryptInterceptor";
    private final String servicePublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAh1y6hCE7VU/UrBHO6BmZeVWVrGw5YlzVEFvbcfKfSst1P0tw5EK6p7ulcWPSy/59tC1MbdiyiZ9+38nRon2KVyIuRnKXb7rtIp2c5RriEZHaIA8qmj75d4PYptssWV0LMLcs+fLx00b4XDI6Q9la/1++Fh/nP4r9QwIyu2QvXCAd3SaQxxr1QdL5ZHDzVmhV7B24dPQiK9Tb7xIqrFMrF7rAr4Be88Kb3ckalKYUH1hn37ZFVG+vjd/7CTBuuueoNjpJ7KlXlBib46Xp3jBlvfbaeKUN9RFl+ebJL5kWPH3LtUD8QjKdCGuCoH20RvCKLI4T1AqgWqTZhJ/rzCSehQIDAQAB";


    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        String aesKeyStr = "";
        String url = request.url().toString();

        //post 方法才需要加密
        if (TextUtils.equals(request.method(), "POST")) {
            try {
                //每次都随机生成AES秘钥
                aesKeyStr = AESUtil.genKeyAES();
                if (TextUtils.isEmpty(request.header("Encrypt"))) {//如果不含有 Encrypt ,说明这请求应该加密
                    Log.d(TAG, "intercept: 该请求要加密：" + url);
                    request = encrypt(request, aesKeyStr);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Response response = chain.proceed(request);
        if (response.header("token") != null) {
            UserProfileManager.getInstance().setUserToken(response.header("token"));
        }
        if (response.header("E") != null) {
            return decrypt(response, aesKeyStr);
        }
        Log.d(TAG, "intercept: 该响应无需解密" + url);
        return response;
    }

    private Request encrypt(Request request, String aesKey) throws Exception {
        RequestBody requestBody = request.body();
        if (requestBody != null) {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);
            Charset charset = Charset.forName("UTF-8");
            MediaType contentType = requestBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(charset);
            }
            String string = buffer.readString(charset);
            String encryptStr = HttpEncryptUtil.appEncrypt(string, servicePublicKey, aesKey);
            RequestBody body = MultipartBody.create(contentType, encryptStr);
            request = request.newBuilder().post(body).build();
        }

        return request;
    }

    private Response decrypt(Response response, String aesKey) throws IOException {
        if (response.isSuccessful()) {
            ResponseBody body = response.body();
            BufferedSource source = body.source();
            source.request(Long.MAX_VALUE); // Buffer the entire body.
            Buffer buffer = source.buffer();
            Charset charset = Charset.defaultCharset();
            MediaType contentType = body.contentType();

            if (contentType != null) {
                charset = contentType.charset(charset);
            }
            String bodyString = buffer.clone().readString(charset);

            try {
                bodyString = HttpEncryptUtil.appDecrypt(bodyString, aesKey);
            } catch (Exception e) {
                e.printStackTrace();
            }

            ResponseBody responseBody = ResponseBody.create(contentType, bodyString);
            response = response.newBuilder().body(responseBody).build();
        }

        return response;
    }

}
